const WXAPI = require('apifm-wxapi')
const app = getApp();
Page({
    data: {
      // formData:{
      //   itemTitle: '',
      //   sellPoint: '',
      //   shareContent: '',
      //   price:'',
      //   stockNum: ''
      // },
      fileList: [],
      fileList1: [],
      // catList: [],
      catNo1:'',
      catAllList: [],
      defaultCat : '',
      type: 'create',
      itemNo: '',
      categories:[],
      showLeiBie:false,
      leibie:'',
      guiGeArr:[{
        id:0,
        stockTitle:'',
        price:'',
        stockNum:'',
        picNo: '',
        narrowPicNo: '',
        fileList:[]
      }],
      btVal:'',
    },
    // 规格库存输入框
    kuCunInp(e){
      let eId = e.currentTarget.dataset.id;
      let value = e.detail.value;
      let guiGeArr = this.data.guiGeArr;
      for(let [index,item] of guiGeArr.entries()){
        if(item.id == eId){
          item.stockNum = value;
        }
      }
      this.setData({
        guiGeArr:guiGeArr
      })
    },
    // 规格价格输入框
    jiaGeInp(e){
      let eId = e.currentTarget.dataset.id;
      let value = e.detail.value;
      let guiGeArr = this.data.guiGeArr;
      for(let [index,item] of guiGeArr.entries()){
        if(item.id == eId){
          item.price = value;
        }
      }
      this.setData({
        guiGeArr:guiGeArr
      })
    },
    // 规格型号输入框
    xingHaoInp(e){
      let eId = e.currentTarget.dataset.id;
      let value = e.detail.value;
      let guiGeArr = this.data.guiGeArr;
      for(let [index,item] of guiGeArr.entries()){
        if(item.id == eId){
          item.stockTitle = value;
        }
      }
      this.setData({
        guiGeArr:guiGeArr
      })
    },
    // 标题输入框
    btInput(e){
      this.setData({ btVal: e.detail.value });
    },
    // 新增规格
    addGuiGe(){
      let guiGeArr = this.data.guiGeArr;
      let len = guiGeArr.length;
      let guige ={
        id: guiGeArr[len - 1].id + 1,
        stockTitle:'',
        price:'',
        stockNum:'',
        picNo: '',
        narrowPicNo: '',
        fileList:[]
      }
      console.log(guige);
      guiGeArr.push(guige);
      this.setData({
        guiGeArr: guiGeArr,
      })
    },
    delGuige(e){
      let eId = e.currentTarget.dataset.id;
      let guiGeArr = this.data.guiGeArr;
      for(let [index,item] of guiGeArr.entries()){
        if(item.id == eId){
          guiGeArr.splice(index,1);
        }
      }
      this.setData({
        guiGeArr:guiGeArr
      })
    },
    onClose() {
      this.setData({ showLeiBie: false });
    },
    onSelect(e) {
      console.log(e.detail);
      this.setData({
        leibie:e.detail
      })
    },
    // 选择类别
    selLeiBie(){
      let that = this;
      if (app.globalData.shopNo && app.globalData.shopNo != '') {
        WXAPI.goodsCategory().then(function (res) {
          let resData = res.data;
          if(res.retCode == 200){
            for(let item of resData){
              item.name = item.catName;
            }
          }
          that.setData({
            categories: resData,
            showLeiBie: true,
          });
        })
      } else {
        setTimeout(function () {
          that.selLeiBie();
        }, 300)
      }
    },
  // catChange(event) {
  //   const { picker, value, index } = event.detail;
  //   const cat = this.data.catAllList[index].catNo
  //   this.setData({
  //     catNo: cat
  //   })
  // },
  getFileList(arrList){
    let newArrList = [];
    if(arrList && arrList != '' && arrList.length > 0){
      newArrList = arrList.map((item) => {
        return {
          ...item,
          url: item.picUrl,
          isImage: true
        }
      })
    }
    return newArrList;
  },
  onLoad(options){
    // console.log(options)
    const { id, type} = options
    if(id){
      WXAPI.goodsInfo(id).then((res) => {
        // console.log(res, this.data)
        if(res.retCode === '200'){
          const dataMap = res.data
          const { itemNo, itemTitle, subTitle, catNo1, catName1, itemSkuResultDtos, itemPicTopResultDtoList,itemPicDetailResultDtoList} = dataMap
          
          console.log(JSON.stringify(dataMap))
          this.setData({
            itemNo: id,
            type: 'edit',
            fileList: this.getFileList(dataMap.itemPicTopResultDtoList),
            fileList1: this.getFileList(dataMap.itemPicDetailResultDtoList),
            btVal:dataMap.itemTitle,
            leibie:{
              catName:dataMap.catName1,
              catNo:dataMap.catNo1,
            },
          })
          let guigeArr1 =[];
          for(let [index, item] of dataMap.itemSkuResultDtos.entries()){
            item.id = index;
            console.log(this.getFileList([item]))
            item.fileList = this.getFileList([item]);

            guigeArr1.push(item)
          }
          this.setData({
            guiGeArr:guigeArr1
          })

        }
      })
    }else{
      this.setData({
        type: 'create'
      })
    }
   
  },
  onShow(){
      let localCurUserInfo = wx.getStorageSync('curUserInfo');
      if(localCurUserInfo.merShopInfos && localCurUserInfo.merShopInfos.length >0){
        app.globalData.shopNo = wx.getStorageSync('_curShop') && wx.getStorageSync('_curShop').shopNo || 0;
      }
    },
    // onChange(event) {
    //   // event.detail 为当前输入的值
      
    //   const { id } = event.target
    //   const { detail } = event
    //   const { itemTitle, sellPoint, shareContent, price, stockNum} = this.data.formData
    //   this.setData({
    //     formData:{
    //       itemTitle: id === 'itemTitle' ? detail : itemTitle,
    //       sellPoint: id === 'sellPoint' ? detail : sellPoint,
    //       shareContent: id === 'shareContent' ? detail : shareContent,
    //       price: id === 'price' ? detail : price,
    //       stockNum: id === 'stockNum' ? detail : stockNum,
    //     }
    //   })
    // },
    afterRead(event) {
      let eIndex = event.currentTarget.dataset.index;
      let type = event.currentTarget.dataset.type;
      const { file } = event.detail;
      
      const _this = this
      console.log(file)
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      file.forEach((item,index) => {
        wx.uploadFile({
          url: 'https://yixuanshow.top/common/file/uploadFile',
          filePath: item.path,
          name: 'file',
          formData: { user: 'test' },
          success(res) {
            const dataMap = res.data
            dataMap && JSON.parse(dataMap) && JSON.parse(dataMap).data && _this.getFile(file[index], JSON.parse(dataMap).data,eIndex,type)
          },
          fail(res) {
            wx.showToast({
              title: res,
            })
          }
        });
      })
    },
  submit(){
    // 整理数据
    let that = this;
    let tData = that.data;
    if(tData.btVal == '' || tData.leibie == '' || tData.fileList.length == 0 || tData.guiGeArr[0].stockTitle=='' || tData.guiGeArr[0].stockNum=='' || tData.guiGeArr[0].price=='' || tData.guiGeArr[0].fileList.length==0){
      app.showLoadText('请完善商品信息');
      return;
    }
    let subData = {};
    subData.shopNo = app.globalData.shopNo;
    subData.itemTitle = tData.btVal;
    subData.catNo1 = tData.leibie.catNo;
    subData.itemPicTopVos = this.getPicUrl(tData.fileList);
    subData.itemPicDetailVos = this.getPicUrl(tData.fileList1);
    let itemSku = [];
    let guiGeArr = tData.guiGeArr;
    for(let [index,item] of guiGeArr.entries()){
      console.log(item)
      item.picNo = item.fileList[0].fileNo || item.fileList[0].picNo;
      item.narrowPicNo = item.fileList[0].narrowPicNo;
      itemSku.push(item);
    }

    // this.createGoods(subData)
    
    if(tData.type === 'edit'){
      subData.itemSkuModiVos = itemSku;
      subData.catNo = tData.catNo;
      this.editGoods(subData)
    }else{
      subData.itemSkuCreateVos = itemSku;
      this.createGoods(subData)
    }


  },
  getPicUrl(file){
    let fileList = file.map((item, index) => {
      return {
        narrowPicNo: item.narrowPicNo || item.narrowPicUrl.split('/')[item.narrowPicUrl.split('/').length - 1],
        picNo: item.fileNo || item.picUrl.split('/')[item.picUrl.split('/').length - 1],
        id:item.id
        // isMain: index < 2 ? '1' : '0'
      }
    })
    return fileList;
  },

  editGoods(postData){
    const params = {...postData, itemNo: this.data.itemNo};
    console.log(JSON.stringify(postData))
    WXAPI.modiGoods(params).then((res) => {
      if (res.retCode === '200'){
        wx.showModal({
          title: '提示',
          content: '修改成功',
          showCancel: false,
          confirmText: '查看',
          success(res) {
            wx.redirectTo({
              url: "/pages/goods-manage/index"
            })
          }
        })
      }else{
        wx.showToast({
          icon:'none',
          title: res.retMsg
        })
      }
    })
  },
  deletPic(e){
    let eIndex = e.currentTarget.dataset.index;
    let type = e.currentTarget.dataset.type;
    const { index } = e.detail
    const tempArr = []
    if(type == 'm'){
      if(eIndex == 0){
        tempArr = this.data.fileList
      }else if(eIndex == 1){
        tempArr = this.data.fileList1
      }
      tempArr.splice(index, 1)
      this.setData({
        fileList: tempArr
      })
    }else{
      let guiGeArr = this.data.guiGeArr;
      for(let [index,item] of guiGeArr.entries()){
        if(item.id == eIndex){
          item.fileList = [];
        }
      }
      this.setData({
        guiGeArr:guiGeArr
      })
    }
    
  },
  createGoods(postData){
    WXAPI.addGoods(postData).then((res) => {
      if (res.retCode === '200'){
        wx.showModal({
          title: '提示',
          content: '创建成功',
          cancelText: '查看商品',
          confirmText: '继续创建',
          success(res) {
            if (res.confirm) {
              const pages = getCurrentPages()
              //声明一个pages使用getCurrentPages方法
              const perpage = pages[pages.length - 1]
              //声明一个当前页面
              perpage.onLoad()
            } else {
              wx.redirectTo({
                url: "/pages/goods-manage/index"
              })
              
            }
          }
        })
      }else{
        wx.showToast({
          icon:'none',
          title: res.retMsg
        })
      }
    })
  },
    getFile(file, fileParams,ind,type){
      // 上传完成需要更新 fileList
      const { fileNo, narrowFileNo} =  fileParams
      // const { fileList = [] } = this.data;
      let fileList = [];
      if(type == 'm'){
        if(ind == 1){
          fileList = this.data.fileList1;
        }else{
          fileList = this.data.fileList;
        }
      }else if (type == 'l'){
        fileList = [];
      }
      
      const fileListNew = fileList.concat(([{ ...file, narrowPicNo: narrowFileNo, fileNo,url: `https://yixuanshow.top/common/file/findByNo/${fileNo}` }]));
      
      if(type == 'm'){
        if(ind == 1){
          this.setData({
            fileList1: fileListNew
          })
        }else{
          this.setData({
            fileList: fileListNew
          })
        }
      }else if (type == 'l'){
        let guiGeArr = this.data.guiGeArr;
        for(let [index,item] of guiGeArr.entries()){
          if(item.id == ind){
            item.fileList = fileListNew;
          }
        }
        this.setData({
          guiGeArr:guiGeArr
        })
      }
      
    }
  })